<template>
  <div class="reports">
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card v-loading="loading" element-loading-text="加载报表数据中...">
          <template #header>
            <div class="card-header">
              <span>数据统计报表</span>
              <el-button v-if="!loading" @click="loadData" size="small" type="primary">刷新数据</el-button>
            </div>
          </template>
          
          <el-row :gutter="20">
            <el-col :span="6">
              <div class="stat-item">
                <div class="stat-number">{{ summary.total_predictions || 0 }}</div>
                <div class="stat-label">总预测次数</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-item">
                <div class="stat-number">{{ summary.verified_predictions || 0 }}</div>
                <div class="stat-label">已验证预测</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-item">
                <div class="stat-number">{{ summary.win_rate || 0 }}%</div>
                <div class="stat-label">中奖率</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-item">
                <div class="stat-number">¥{{ summary.total_win_amount || 0 }}</div>
                <div class="stat-label">总中奖金额</div>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>
    
    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="12">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>中奖等级统计</span>
            </div>
          </template>
          
          <div ref="winLevelChart" style="height: 300px;"></div>
        </el-card>
      </el-col>
      
      <el-col :span="12">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>月度统计</span>
            </div>
          </template>
          
          <div ref="monthlyChart" style="height: 300px;"></div>
        </el-card>
      </el-col>
    </el-row>
    
    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="24">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>预测趋势分析</span>
            </div>
          </template>
          
          <div ref="trendChart" style="height: 400px;"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { ref, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import api from '@/api'

export default {
  name: 'Reports',
  setup() {
    const summary = ref({})
    const winningAnalysis = ref({})
    const trends = ref([])
    
    const winLevelChart = ref(null)
    const monthlyChart = ref(null)
    const trendChart = ref(null)
    
    let winLevelChartInstance = null
    let monthlyChartInstance = null
    let trendChartInstance = null
    
    const loading = ref(false)
    
    const loadData = async () => {
      loading.value = true
      try {
        console.log('[Reports] 开始加载报表数据')
        
        // 设置默认数据
        summary.value = {
          total_predictions: 0,
          verified_predictions: 0,
          win_rate: 0,
          total_win_amount: 0
        }
        
        winningAnalysis.value = {
          total_verified: 0,
          total_wins: 0,
          total_amount: 0,
          win_levels: {
            '一等奖': 0,
            '二等奖': 0,
            '三等奖': 0,
            '四等奖': 0,
            '五等奖': 0,
            '六等奖': 0
          },
          monthly_stats: {}
        }
        
        trends.value = []
        
        // 尝试加载数据
        try {
          const summaryResponse = await api.reports.getSummary()
          summary.value = summaryResponse.data
          console.log('[Reports] 汇总数据加载成功:', summary.value)
        } catch (error) {
          console.error('[Reports] 汇总数据加载失败:', error)
        }
        
        try {
          const winningResponse = await api.reports.getWinningAnalysis()
          winningAnalysis.value = winningResponse.data
          console.log('[Reports] 中奖分析数据加载成功:', winningAnalysis.value)
        } catch (error) {
          console.error('[Reports] 中奖分析数据加载失败:', error)
        }
        
        try {
          const trendsResponse = await api.reports.getPredictionTrends()
          trends.value = trendsResponse.data.trends || []
          console.log('[Reports] 趋势数据加载成功:', trends.value)
        } catch (error) {
          console.error('[Reports] 趋势数据加载失败:', error)
        }
        
        // 渲染图表
        await nextTick()
        renderCharts()
        
      } catch (error) {
        console.error('[Reports] 加载报表数据失败:', error)
        ElMessage.error('加载报表数据失败，请刷新页面重试')
      } finally {
        loading.value = false
      }
    }
    
    const renderCharts = () => {
      renderWinLevelChart()
      renderMonthlyChart()
      renderTrendChart()
    }
    
    const renderWinLevelChart = () => {
      if (!winLevelChart.value) return
      
      if (winLevelChartInstance) {
        winLevelChartInstance.dispose()
      }
      
      winLevelChartInstance = echarts.init(winLevelChart.value)
      
      const data = winningAnalysis.value.win_levels || {}
      const chartData = Object.entries(data).map(([name, value]) => ({
        name,
        value
      }))
      
      // 如果没有数据，显示空状态
      if (chartData.every(item => item.value === 0)) {
        const option = {
          title: {
            text: '暂无中奖数据',
            left: 'center',
            top: 'center',
            textStyle: {
              color: '#999',
              fontSize: 14
            }
          }
        }
        winLevelChartInstance.setOption(option)
        return
      }
      
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left'
        },
        series: [
          {
            name: '中奖等级',
            type: 'pie',
            radius: '50%',
            data: chartData,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      }
      
      winLevelChartInstance.setOption(option)
    }
    
    const renderMonthlyChart = () => {
      if (!monthlyChart.value) return
      
      if (monthlyChartInstance) {
        monthlyChartInstance.dispose()
      }
      
      monthlyChartInstance = echarts.init(monthlyChart.value)
      
      const monthlyStats = winningAnalysis.value.monthly_stats || {}
      const months = Object.keys(monthlyStats).sort()
      
      // 如果没有数据，显示空状态
      if (months.length === 0) {
        const option = {
          title: {
            text: '暂无月度数据',
            left: 'center',
            top: 'center',
            textStyle: {
              color: '#999',
              fontSize: 14
            }
          }
        }
        monthlyChartInstance.setOption(option)
        return
      }
      
      const predictions = months.map(month => monthlyStats[month].predictions)
      const wins = months.map(month => monthlyStats[month].wins)
      const amounts = months.map(month => monthlyStats[month].amount)
      
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999'
            }
          }
        },
        legend: {
          data: ['预测次数', '中奖次数', '中奖金额']
        },
        xAxis: {
          type: 'category',
          data: months,
          axisPointer: {
            type: 'shadow'
          }
        },
        yAxis: [
          {
            type: 'value',
            name: '次数',
            position: 'left'
          },
          {
            type: 'value',
            name: '金额',
            position: 'right'
          }
        ],
        series: [
          {
            name: '预测次数',
            type: 'bar',
            data: predictions
          },
          {
            name: '中奖次数',
            type: 'bar',
            data: wins
          },
          {
            name: '中奖金额',
            type: 'line',
            yAxisIndex: 1,
            data: amounts
          }
        ]
      }
      
      monthlyChartInstance.setOption(option)
    }
    
    const renderTrendChart = () => {
      if (!trendChart.value) return
      
      if (trendChartInstance) {
        trendChartInstance.dispose()
      }
      
      trendChartInstance = echarts.init(trendChart.value)
      
      // 如果没有数据，显示空状态
      if (!trends.value || trends.value.length === 0) {
        const option = {
          title: {
            text: '暂无趋势数据',
            left: 'center',
            top: 'center',
            textStyle: {
              color: '#999',
              fontSize: 14
            }
          }
        }
        trendChartInstance.setOption(option)
        return
      }
      
      const dates = trends.value.map(item => item.date)
      const predictions = trends.value.map(item => item.predictions)
      const wins = trends.value.map(item => item.wins)
      const amounts = trends.value.map(item => item.amount)
      
      const option = {
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['预测次数', '中奖次数', '中奖金额']
        },
        xAxis: {
          type: 'category',
          data: dates
        },
        yAxis: [
          {
            type: 'value',
            name: '次数'
          },
          {
            type: 'value',
            name: '金额',
            position: 'right'
          }
        ],
        series: [
          {
            name: '预测次数',
            type: 'line',
            data: predictions
          },
          {
            name: '中奖次数',
            type: 'line',
            data: wins
          },
          {
            name: '中奖金额',
            type: 'line',
            yAxisIndex: 1,
            data: amounts
          }
        ]
      }
      
      trendChartInstance.setOption(option)
    }
    
    const handleResize = () => {
      if (winLevelChartInstance) {
        winLevelChartInstance.resize()
      }
      if (monthlyChartInstance) {
        monthlyChartInstance.resize()
      }
      if (trendChartInstance) {
        trendChartInstance.resize()
      }
    }
    
    onMounted(() => {
      loadData()
      window.addEventListener('resize', handleResize)
    })
    
    return {
      summary,
      loading,
      winLevelChart,
      monthlyChart,
      trendChart
    }
  }
}
</script>

<style scoped>
.reports {
  padding: 20px;
}

.card-header {
  font-weight: bold;
  color: #333;
}

.stat-item {
  text-align: center;
  padding: 20px;
}

.stat-number {
  font-size: 32px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 10px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}
</style> 